package com.hxit.huaxiamelongarden.common;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json; charset=UTF-8");
        String requestURI = request.getRequestURI();

        // 排除不需要验证的路径
        if (requestURI.equals("/login") || requestURI.equals("/register") ||
                requestURI.equals("/captcha") || requestURI.startsWith("/doc.html") ||
                requestURI.startsWith("/webjars") || requestURI.startsWith("/v3/api-docs") || requestURI.startsWith("/ws")) {
            return true; // 放行
        }

        String userId = (String) request.getAttribute("userId");
        if (userId != null) {
            logger.info("用户ID：{} 已通过认证", userId); // 打印中文日志
            return true; // 用户已登录，放行
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("用户未登录或令牌无效。");
            logger.warn("未认证用户访问，缺少有效的用户ID"); // 打印中文日志
            return false; // 拦截
        }
    }
}

